package j.quartz.ui.sys.shiro.realm;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import j.quartz.sys.user.SysUserService;
import j.quartz.sys.user.entity.SysUser;
import j.quartz.ui.common.utils.SysUserUtil;


@Component
public class SysUserRealm extends AuthorizingRealm {
	
	private SysUserService sysUserService ;

	/**
	 * 授权的回调方法
	 * 将角色和权限（这里是菜单）授权给当前登录的用户
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		System.out.println("username ： "+username);
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 根据用户名查询当前用户拥有的角色
		Set<String> roleNames = new HashSet<String>();
		roleNames.add("admin");
		roleNames.add("wator");
		// 将角色名称提供给info
		authorizationInfo.setRoles(roleNames);
		// 根据用户名查询当前用户权限
		Set<String> permissionNames = new HashSet<String>();
		permissionNames.add("add");
		permissionNames.add("delete");
		permissionNames.add("edit");
		permissionNames.add("select");
		// 将权限名称提供给info
		authorizationInfo.setStringPermissions(permissionNames);

		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		SysUser user = sysUserService.getOneByUsername(username);
		if (user == null) {
			// 用户名不存在抛出异常
			throw new UnknownAccountException();
		}

		if (user.getSts() == "0") {
			// 用户被管理员锁定抛出异常
			throw new LockedAccountException();
		}

		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user.getUsername(),
				user.getPassword(), 
				ByteSource.Util.bytes(user.getCredentialsSalt()), 
				getName());

		return authenticationInfo;
	}


	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

	@Override
	public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
		super.clearCachedAuthenticationInfo(principals);
	}

	@Override
	public void clearCache(PrincipalCollection principals) {
		super.clearCache(principals);
	}

	public void clearAllCachedAuthorizationInfo() {
		getAuthorizationCache().clear();
	}

	public void clearAllCachedAuthenticationInfo() {
		getAuthenticationCache().clear();
	}

	public void clearAllCache() {
		clearAllCachedAuthenticationInfo();
		clearAllCachedAuthorizationInfo();
	}
	
	
	/**
	 * 授权用户信息
	 */
	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;

		private String uuid; // 编号
		private String username; // 登录名
		private String nickNm; // 姓名
		private boolean mobileLogin; // 是否手机登录

		public Principal(SysUser user, boolean mobileLogin) {
			this.uuid = user.getUuid();
			this.username = user.getUsername();
			this.nickNm = user.getNickNm();
			this.mobileLogin = mobileLogin;
		}


		public String getUuid() {
			return uuid;
		}

		public String getNickNm() {
			return nickNm;
		}

		public String getUsername() {
			return username;
		}

		public boolean isMobileLogin() {
			return mobileLogin;
		}

		/**
		 * 获取SESSIONID
		 */
		public String getSessionid() {
			try {
				return (String) SysUserUtil.getSession().getId();
			} catch (Exception e) {
				return "";
			}
		}

		@Override
		public String toString() {
			return "Principal [uuid=" + uuid + ", username=" + username + ", nickNm=" + nickNm + ", mobileLogin="
					+ mobileLogin + "]";
		}


	}
}
